package com.tcs.test.netty.client;

import com.tcs.model.ipdata.IpDataBean;
import com.tcs.test.netty.client.channelinit.MyChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 客户端
 */
public class NettyClient {

    private final Logger logger = LoggerFactory.getLogger(NettyClient.class);

    private final Object lock = new Object();

    private static final EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

    public static Bootstrap getBootstrap() {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .remoteAddress("192.168.0.100",5666)
                .handler(new MyChannelInitializer());
        return bootstrap;
    }

    public void go() {
        try {
            Bootstrap bootstrap = getBootstrap();
            ChannelFuture channelFuture = bootstrap.connect();
            channelFuture.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        logger.info("重连中!");
                        go();
                    }
                }
            });
            IpDataBean ipDataBean = new IpDataBean("123",123);
            channelFuture.channel().writeAndFlush(ipDataBean).addListener(ChannelFutureListener.CLOSE);
        } catch (Exception e) {
            logger.error("", e);
        }
    }

   public static void main(String args[]) {
        new NettyClient().go();
    }
}
